package com.plugin.sproutcore.ui.dialogs;

import java.io.IOException;
import java.util.Iterator;
import java.util.TreeSet;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.dialogs.ContainerSelectionDialog;
import org.eclipse.ui.dialogs.PropertyPage;
import org.eclipse.ui.dialogs.ResourceSelectionDialog;
import org.eclipse.ui.dialogs.SelectionDialog;

import com.plugin.sproutcore.core.resources.SproutCoreContext;
import com.plugin.sproutcore.core.resources.properties.PropertiesLoader;
import com.plugin.sproutcore.core.resources.properties.SproutCoreProject;
import com.plugin.sproutcore.core.resources.properties.SproutCoreProperties;
import com.plugin.sproutcore.util.ProjectUtil;
import com.plugin.sproutcore.util.SproutCoreUtil;

public class SproutCorePropertyPage extends PropertyPage 
{
	private SproutCoreContext context;
	private SproutCoreProperties properties;
	
	private Tree appList;
	
	@Override
	protected Control createContents(Composite parent) 
	{
		Composite composite = new Composite(parent, SWT.NONE);
        composite.setLayout(new FillLayout());
        
		try 
		{
			IProject project = (IProject)getElement();
			
			context = new SproutCoreContext(project);
			properties = context.getProperties();
			
			addAppPanel(composite);
		} 
		catch (CoreException e) 
		{
            Text text = new Text(composite, SWT.BORDER | SWT.MULTI | SWT.READ_ONLY);
            text.setText(e.toString());
            return composite;
		}
		
        noDefaultAndApplyButton();
        
        return composite;
	}
	
	private void addAppPanel(Composite parent) 
	throws CoreException
	{
		Composite composite = new Composite(parent, SWT.FILL);
		composite.setLayout(new GridLayout(2, false));
		
        Label text = new Label(composite, SWT.NONE);
        text.setText("Location of SproutCore projects:");
        GridData gd = new GridData(SWT.NONE);
    	gd.horizontalSpan = 2;
        text.setLayoutData(gd);
		
        appList = new Tree(composite, SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | 
        		SWT.V_SCROLL);
        appList.setLayoutData(new GridData(
            GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL |
            GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL
        ));

		Composite buttons = new Composite(composite, SWT.NONE);
		buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
		buttons.setLayout(new FillLayout(SWT.VERTICAL));
        
        Button addButton = new Button(buttons, SWT.PUSH);
        addButton.setText("Add Folder...");
        addButton.addSelectionListener(new SelectionAdapter() {
        	
        	@Override
        	public void widgetSelected(SelectionEvent e) 
        	{
        		try {
					handleBrowse();
				} catch (CoreException ex) {
					ex.printStackTrace();
				}
        	}
        	
		});
        
        Button editButton = new Button(buttons, SWT.PUSH);
        editButton.setText("Edit...");
        
        Button removeButton = new Button(buttons, SWT.PUSH);
        removeButton.setText("Remove");
        removeButton.setEnabled(false);
        
        refresh();
	}
	
	private void refresh() throws CoreException
	{
        Iterator<SproutCoreProject> itr = properties.getScProjects().iterator();
        while (itr.hasNext())
        {
        	addSourceFolderTreeItem(itr.next());
        }
	}
	
	private void handleBrowse() throws CoreException
	{
		IContainer root = (IContainer)getElement();
		SelectionDialog dialog = new ResourceSelectionDialog(
				this.getShell(), root, "Select project");
		
		if (dialog.open() == ContainerSelectionDialog.OK) 
		{
			Object[] result = dialog.getResult();
			if (result.length == 1) 
			{
				IPath path = (Path) result[0];
				IResource resource = root.findMember(path.toString());
				if (resource != null) 
				{
					SproutCoreProject scProject;
					scProject = SproutCoreUtil.createSproutCoreProject(resource);
					properties.getScProjects().add(scProject);
					try {
						PropertiesLoader.save(root.getProject(), properties);
					} 
					catch (IOException e) {
						IStatus status = ProjectUtil.createErrorStatus(e.getMessage());
						throw new CoreException(status);
					}
					refresh();
				}
			}
		}
	}
	
	private TreeItem addSourceFolderTreeItem(SproutCoreProject project) 
	throws CoreException 
	{
		TreeItem root = new TreeItem(appList, SWT.NONE);
		IPath projectPath = Path.fromPortableString(project.getPath());
		root.setText(getNodeText(project.getName(), projectPath.toOSString()));
        
		IContainer[] appFiles = project.getApps(context.getProject());
		TreeItem appRoot;
        for (IContainer appFile:appFiles)
        {
        	appRoot = new TreeItem(root, SWT.NONE);
        	appRoot.setText(getNodeText(appFile.getName(),
    				appFile.getProjectRelativePath().toOSString()));
        }
        root.setExpanded(true);
        
        return root;
	}
	
	private String getNodeText(String name, String path)
	{
		StringBuilder builder = new StringBuilder();
		builder.append(name);
		if (path.length() > 0) {
			builder.append(" (");
			builder.append(path);
			builder.append(")");
		}
		return builder.toString();
	}
	
	public TreeSet<SproutCoreProject> getProjects() 
	{
		return properties.getScProjects();
	}
	
	public IProject getProject()
	{
		return (IProject) getElement();
	}
	

}
